<template>
  <div id="map_dom">
    <div id="map" ref="rootmap">
      <div id="legend" class="info legend"></div>
    </div>
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import "ol/ol.css";
import { Map, View } from "ol"; // 确保导入 OverviewMap
import Overlay from "ol/Overlay";
import { XYZ, Vector as VectorSource } from "ol/source";
import { fromLonLat } from "ol/proj";
import { ZoomSlider, ZoomToExtent, OverviewMap } from "ol/control";
import { Style, Fill, Stroke, Circle } from "ol/style";
import { Vector as VectorLayer, Image as ImageLayer, Tile as TileLayer } from "ol/layer";
import { GeoJSON } from "ol/format";

// 定义 props
const props = defineProps({
  vectLayoutGeojson: {
    type: Object,
    default: () => { }
  },
  legendGrades: {
    type: Array,
    default: () => ["大于-85", "-95 ~ -85", "-100 ~ -95"]
  }
});

// 定义响应式数据
const map = ref(null);
const rootmap = ref(null);

const token = '46045620188f7bdcb573dda2f84fb29a'

const initMap = () => {
  const e_4326 = [100.428571, 19.62, 158.928571, 53.52];

  map.value = new Map({
    target: rootmap.value,
    layers: [
      new TileLayer({
        title: "TianDi1",
        source: new XYZ({
          url: "http://t{0-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + token
        })
      }),
      new TileLayer({
        title: "TianDi2",
        source: new XYZ({
          url: "http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + token
        })
      })
    ],
    view: new View({
      projection: "EPSG:3857",
      center: fromLonLat([121.561099, 29.871172]),
      zoom: 10
    })
  });

  // 创建鹰眼地图控件
  const overviewMap = new OverviewMap({
    className: "ol-overviewmap ol-custom-overviewmap",
    layers: [
      new TileLayer({
        title: "TianDi1",
        source: new XYZ({
          url: "http://t{0-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + token
        })
      })
    ],
    collapseLabel: "\u00BB",
    label: "\u00AB",
    collapsed: false
  });

  // 将鹰眼地图控件添加到地图上
  map.value.addControl(overviewMap);
  // 添加缩放滑块
  map.value.addControl(new ZoomSlider());
  // 添加缩放至指定范围
  map.value.addControl(
    new ZoomToExtent({
      extent: [13400000, 3400000, 13600000, 3600000],
    })
  );
};

const loadStyle = (color, type) => {
  let image = new Circle({
    radius: 3,
    fill: new Fill({ color: color }),
    stroke: new Stroke({ color: color, width: 1 })
  });
  let styles = {
    Point: [
      new Style({
        image: image // 点样式
      })
    ],
    LineString: [
      new Style({
        stroke: new Stroke({
          // 线的边界样式
          color: color,
          width: 1
        })
      })
    ],
    MultiLineString: [
      new Style({
        stroke: new Stroke({
          // 多线的边界样式
          color: color,
          width: 1
        })
      })
    ],
    MultiPoint: [
      new Style({
        image: image // 多点的点样式
      })
    ],
    MultiPolygon: [
      new Style({
        stroke: new Stroke({
          color: color,
          width: 1
        }),
        fill: new Fill({
          // 多区的填充样式
          color: "rgba(255, 255, 0, 0.1)"
        })
      })
    ],
    Polygon: [
      new Style({
        stroke: new Stroke({
          // 区的边界样式
          color: color,
          width: 1
        }),
        fill: new Fill({
          // 区的填充样式
          color: "rgba(0, 0, 255, 0.1)"
        })
      })
    ],
    GeometryCollection: [
      new Style({
        stroke: new Stroke({
          // 集合要素的边界样式
          color: color,
          width: 2
        }),
        fill: new Fill({
          // 集合要素的填充样式
          color: color
        }),
        image: new Circle({
          // 集合要素的点样式
          radius: 10,
          fill: null,
          stroke: new Stroke({
            color: color
          })
        })
      })
    ],
    Circle: [
      new Style({
        stroke: new Stroke({
          // 圆的边界样式
          color: color,
          width: 2
        }),
        fill: new Fill({
          // 圆的填充样式
          color: color
        })
      })
    ]
  };
  return styles[type];
};

const styleFunction = (feature) => {
  let color = loadStyle(
    feature.getProperties().color || "red",
    feature.getGeometry().getType()
  );
  return color;
};

const loadVectData = () => {
  // console.log('vectLayoutGeojson', props.vectLayoutGeojson)

  // 将 GeoJSON 数据转换为 OpenLayers 的 Feature 对象
  const features = new GeoJSON().readFeatures(props.vectLayoutGeojson, {
    featureProjection: 'EPSG:3857' // 设置投影
  })
  // console.log('features', features)

  // 创建矢量图层并添加到地图
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features
    }),
    style: styleFunction // 样式设置
  });

  map.value.addLayer(vectorLayer);
}

const initLegend = () => {
  //let grades = ["大于-85", "-95 ~ -85", "-100 ~ -95"];
  let grades = props.legendGrades
  let colors = ["red", "orange", "yellow"];
  let labels = [];
  for (let i = 0; i < grades.length; i++) {
    labels.push('<i style="background:' + colors[i] + '"></i> ' + grades[i]);
  }
  document.getElementById("legend").innerHTML = labels.join("<br>");
}

const initPopup = () => {
  // console.log("initPopup")

  var container = document.getElementById("popup");
  var closer = document.getElementById("popup-closer");
  var content = document.getElementById("popup-content");
  // 创建一个弹窗 Overlay 对象
  let overlay = new Overlay({
    element: container, //绑定 Overlay 对象和 DOM 对象的
    autoPan: true, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
    autoPanAnimation: {
      duration: 250, //自动平移效果的动画时间 9毫秒
    },
  });
  // 将弹窗添加到 map 地图中
  map.value.addOverlay(overlay);

  map.value.on("click", function (evt) {
    console.log("evt", evt)
    let feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature) {
      return feature;
    });
    if (feature) {
      // 修改 featureItemData 的格式
      let featureItemData = {
        avg_noise: feature.get("avg_noise"),
        cell_c_name: feature.get("cell_c_name"),
        cgi: feature.get("cgi"),
        city_c_name: feature.get("city_c_name"),
        color: feature.get("color"),
        eci: feature.get("eci"),
        frequency: feature.get("frequency"),
        prod_c_name: feature.get("prod_c_name")
      };

      if (!featureItemData.cgi) {
        return
      }

      content.innerHTML = [
        `<h4>${featureItemData.cell_c_name}</h4>`,
        `<h5>产品名称: ${featureItemData.prod_c_name}</h5>`,
        `<h5>avg-noise: ${featureItemData.avg_noise}</h5>`,
        `<h5>ECI: ${featureItemData.eci}</h5>`,
        `<h5>CGI: ${featureItemData.cgi}</h5>`,
        `<h5>城市名称: ${featureItemData.city_c_name}</h5>`,
        `<h5>频率: ${featureItemData.frequency}</h5>`,
      ].join("");
      overlay.setPosition(evt.coordinate);
    }
  })

  closer.onclick = function () {
    overlay.setPosition(undefined);
    closer.blur();
    return false;
  };
}

onMounted(() => {
  initMap();
  // initLegend()
  // loadVectData()
  // initPopup()
});
</script>

<style>
#map_dom,
#map {
  width: 100%;
  height: 96.5vh;
  position: relative;
  cursor: pointer;
}

/**
* 缩放滑块控件ZoomSlider的样式，放置到缩放按钮之间实现导航条功能
*/
#map .ol-zoom .ol-zoom-out {
  margin-top: 204px;
}

#map .ol-zoomslider {
  background-color: transparent;
  top: 2.3em;
}

#map .ol-touch .ol-zoom .ol-zoom-out {
  margin-top: 212px;
}

#map .ol-touch .ol-zoomslider {
  top: 2.75em;
}

#map .ol-zoom-in.ol-has-tooltip:hover [role="tooltip"],
#map .ol-zoom-in.ol-has-tooltip:focus [role="tooltip"] {
  top: 3px;
}

#map .ol-zoom-out.ol-has-tooltip:hover [role="tooltip"],
#map .ol-zoom-out.ol-has-tooltip:focus [role="tooltip"] {
  top: 232px;
}

#map .ol-zoom-extent {
  top: 280px;
}

.ol-custom-overviewmap,
.ol-custom-overviewmap.ol-uncollapsible {
  bottom: auto;
  left: auto;
  right: 0;
  /* 右侧显示 */
  top: 0;
  /* 顶部显示 */
}

/* 鹰眼控件展开时控件外框的样式 */
.ol-custom-overviewmap:not(.ol-collapsed) {
  border: 1px solid black;
}

/* 鹰眼控件中地图容器样式 */
.ol-custom-overviewmap .ol-overviewmap-map {
  border: none;
}

/* 鹰眼控件中显示当前窗口中主图区域的边框 */
.ol-custom-overviewmap .ol-overviewmap-box {
  border: 2px solid red;
}

/* 鹰眼控件展开时其控件按钮图标的样式 */
.ol-custom-overviewmap:not(.ol-collapsed) button {
  bottom: auto;
  left: auto;
  right: 1px;
  top: 1px;
}

.layer-switcher {
  top: auto;
  bottom: 50px;
}

.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  /* display: none; */
}

.ol-popup h5 {
  margin-block-start: 0.5em;
  margin-block-end: 0.5em;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.popup-content {
  width: 250px;

  h4 {
    font-size: 14px;
  }

  h5 {
    font-weight: initial;
    font-size: 13px;
  }
}

.ol-popup-closer:after {
  content: "✖";
}

.info {
  width: 100px;
  min-width: 120px;
  padding: 6px 8px;
  font: 14px/16px Arial, Helvetica, sans-serif;
  background: white;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  z-index: 99999;
  position: absolute;
  bottom: 1px;
  left: 1px;
}

.info h4 {
  margin: 0 0 5px;
  color: #777;
}

.legend {
  text-align: left;
  line-height: 18px;
  color: #555;
}

.legend i {
  width: 18px;
  height: 18px;
  float: left;
  margin-right: 8px;
  opacity: 0.7;
}
</style>